package schoolsys.dao;








import schoolsys.util.ConfigerManger;

import java.sql.*;

/**
 * author:wxy
 * create_Date:2021/10/19 11:05
 * 连接数据库
 * tb_name:student
 */
public class BaseDao {
    private Connection conn;
    private ResultSet res;
    private PreparedStatement ps;

    /**
     * 获取连接
     * @return
     */
    public boolean  getConnection(){
        String userName= ConfigerManger.getConfigerManger().getString("username");
        String url= ConfigerManger.getConfigerManger().getString("url");
        String password= ConfigerManger.getConfigerManger().getString("password");
        String driver= ConfigerManger.getConfigerManger().getString("driver");
        try {
            Class.forName(driver);
            conn= DriverManager.getConnection(url,userName,password);
            return true;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return false;
        }
    }

    /**
     * 查询操作
     * @param sql
     * @param params
     * @return
     */
    public  ResultSet excuteQuerySql(String sql,Object ...params){
        try {
            ps=conn.prepareStatement(sql);
            for (int i = 0; i <params.length ; i++) {
                ps.setObject(i+1,params[i]);
            }
            res=ps.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return res;
    }

    /**
     * 更新操作
     * @param sql
     * @param params
     * @return
     */
    public int excuteUpdateSql(String sql,Object ...params){
        int n=0;
        try {
            ps=conn.prepareStatement(sql);
            for (int i = 0; i <params.length ; i++) {
                ps.setObject(i+1,params[i]);
            }
            n=ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return n;
    }

    /**
     * 关闭资源
     * @return
     */
    public boolean closeSourses(){
        try {
            if(res!=null){
                res.close();
            }
            if(ps!=null){
                ps.close();
            }
            if(conn!=null){
                conn.close();
            }
           return true;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return false;
        }
    }

}
